package com.mind.adjust.service.impl;

import com.mind.adjust.mapper.AjRuleDetailMapper;
import com.mind.api.serivce.ITongweiMessage;
import com.mind.common.core.domain.model.LoginUser;
import com.mind.common.utils.DateUtils;
import com.mind.common.utils.SecurityUtils;
import com.mind.customer.mapper.AjRuleMapper;
import com.mind.system.domain.AjRuleCheck;
import com.mind.adjust.domain.vo.PatchUpdate;
import com.mind.adjust.mapper.AjRuleCheckMapper;
import com.mind.adjust.service.AjRuleCheckService;
import com.mind.common.exception.ServiceException;
import com.mind.common.utils.StringUtils;
import com.mind.system.domain.AjRule;
import com.mind.system.domain.AjRuleDetail;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;


/**
 * 规则复核(AjRuleCheck)表服务实现类
 *
 * @author makejava
 * @since 2024-12-12 11:04:44
 */
@Service("ruleCheckService")
public class AjRuleCheckServiceImpl implements AjRuleCheckService {
    @Autowired
    private AjRuleCheckMapper ruleCheckMapper;
    @Resource
    private AjRuleMapper ruleMapper;

    @Resource
    private ITongweiMessage tongweiMessage;
    @Resource
    private AjRuleDetailMapper ruleDetailMapper;

    /**
     * 查询规则复核信息集合
     *
     * @param ruleCheck 规则复核信息
     * @return 规则复核信息集合
     */
    @Override
    public List<AjRuleCheck> selectRuleCheckList(AjRuleCheck ruleCheck) {
        return ruleCheckMapper.selectRuleCheckList(ruleCheck);
    }

    /**
     * 通过规则复核ID查询规则复核信息
     *
     * @param ruleCheckId 规则复核ID
     * @return 角色对象信息
     */
    @Override
    public AjRuleCheck selectRuleCheckById(Long ruleCheckId) {
        return ruleCheckMapper.selectRuleCheckById(ruleCheckId);
    }

    /**
     * 删除规则复核信息
     *
     * @param ruleCheckId 规则复核ID
     * @return 结果
     */
    @Override
    public int deleteRuleCheckById(Long ruleCheckId) {
        return ruleCheckMapper.deleteRuleCheckById(ruleCheckId);
    }

    /**
     * 批量删除规则复核信息
     *
     * @param ruleCheckIds 需要删除的规则复核ID
     * @return 结果
     */
    @Override
    public int deleteRuleCheckByIds(Long[] ruleCheckIds) {
        return ruleCheckMapper.deleteRuleCheckByIds(ruleCheckIds);
    }

    /**
     * 新增保存规则复核信息
     *
     * @param ruleCheck 规则复核信息
     * @return 结果
     */
    @Override
    public int insertRuleCheck(AjRuleCheck ruleCheck) {
        return ruleCheckMapper.insertRuleCheck(ruleCheck);
    }

    /**
     * 修改保存规则复核信息
     *
     * @param ruleCheck 规则复核信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRuleCheck(AjRuleCheck ruleCheck) {
        if (StringUtils.isEmpty(ruleCheck.getStatus())) {
            throw new ServiceException("状态不能为空");
        }
        AjRuleCheck ajRuleCheck = ruleCheckMapper.selectRuleCheckById(ruleCheck.getRuleId().longValue());
        if (ajRuleCheck == null) {
            throw new ServiceException("该规则复核不存在");
        }

        // 如果状态为5，则表示复核通过，需要更新状态
        if (ruleCheck.getStatus().equals("5")) {
            ruleMapper.updateRule(new AjRule() {{
                setId(ruleCheck.getRuleId());
                setStatus("2");
            }});
        }
        return ruleCheckMapper.updateRuleCheck(ruleCheck);
    }

    /**
     * 批量插入
     *
     * @param ruleCheckList 附件类型信息
     * @return 结果
     */
    @Override
    public int batchInsert(List<AjRuleCheck> ruleCheckList) {
        int size = 0;
        for (AjRuleCheck ruleCheck : ruleCheckList) {
            if (ruleCheckMapper.selectRuleCheckByName(ruleCheck.getName()) == null) {
                ruleCheckMapper.insertRuleCheck(ruleCheck);
                size++;
            }
        }
        return size;
    }

    @Override
    public int patchCheck(PatchUpdate params) {
        for(Long id : params.getIdList()){
            AjRuleCheck ajRuleCheck = ruleCheckMapper.selectRuleCheckById(id);
            if (ajRuleCheck == null) {
                throw new ServiceException("该规则复核不存在");
            }
            if(ajRuleCheck.getStatus().equals("3")){
                throw new ServiceException("该规则复核已通过，不能重复提交");
            }
            if(ajRuleCheck.getStatus().equals("4")){
                throw new ServiceException("该规则复核已驳回，不能重复提交");
            }
            AjRule ruleParams = new AjRule(){{
                setId(ajRuleCheck.getRuleId());
            }};
            List<AjRule> ajRules = ruleMapper.selectRuleByParams(ruleParams);
            if(CollectionUtils.isEmpty(ajRules)){
                throw new ServiceException("该规则配置不存在");
            }
            AjRule ajRule = ajRules.get(0);
            // 立即失效
            String ruleStatus = "2";
            // 如果状态为5，则表示复核通过，需要更新状态
            if (ajRuleCheck.getStatus().equals("5")) {
                ruleMapper.updateRule(new AjRule() {{
                    setId(ajRuleCheck.getRuleId());
                    setStatus("2");
                }});
            }
            // 通过且没有生效时间立即生效
            else if(params.getStatus().equals("3")){
                // 老版本生成历史版本
                if(!ajRule.getIsAdd().equals("1")) {
                    AjRuleCheck oldRuleCheck = new AjRuleCheck();
                    copyRuleDetail(ajRule, oldRuleCheck);
                    BeanUtils.copyProperties(ajRule, oldRuleCheck);
                    if(ajRuleCheck.getActiveDate().getTime() > DateUtils.toDate(LocalDate.now()).getTime()){
                        ruleStatus = "1";
                        oldRuleCheck.setExpireDate(DateUtils.addDays(ajRuleCheck.getActiveDate(),-1));
                    }
                    oldRuleCheck.setRuleStatus(ruleStatus);
                    oldRuleCheck.setUuid(ajRuleCheck.getUuid());
                    oldRuleCheck.setRuleId(ajRuleCheck.getRuleId());
                    oldRuleCheck.setStatus("8");
                    ruleCheckMapper.insertRuleCheck(oldRuleCheck);
                }
                // 更新新版本的数据
                AjRule rule = new AjRule();
                BeanUtils.copyProperties(ajRuleCheck, rule);
                String status = DateUtils.parseDateToStr("yyyy-MM-dd", ajRuleCheck.getActiveDate()).equals(LocalDate.now().toString()) ? "1": "9";
                rule.setId(ajRule.getId());
                rule.setStatus(status);
                rule.setIsAdd("0");
                ruleMapper.updateRule(rule);
                String content = String.format("[%s] 复核通过, 即将在[%s]生效。", rule.getRuleDetailName(), DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", rule.getActiveDate()));
                //tongweiMessage.sendMessage("复核通过", content);
            }else if(params.getStatus().equals("4")){
                String status = "1";
                if(StringUtils.isNotEmpty(ajRule.getIsAdd()) && ajRule.getIsAdd().equals("1")){
                    status = "3";
                }
                String finalStatus = status;
                ruleMapper.updateRule(new AjRule(){{
                    setId(ajRule.getId());
                    setStatus(finalStatus);
                }});
                // 新版本生成历史版本
                if(!ajRule.getIsAdd().equals("1")) {
                    AjRuleCheck oldRuleCheck = new AjRuleCheck();
                    BeanUtils.copyProperties(ajRuleCheck, oldRuleCheck);
                    oldRuleCheck.setRuleStatus("10");
                    oldRuleCheck.setUuid(ajRuleCheck.getUuid());
                    oldRuleCheck.setRuleId(ajRuleCheck.getRuleId());
                    oldRuleCheck.setRemark(params.getRemark());
                    oldRuleCheck.setStatus("8");
                    ruleCheckMapper.insertRuleCheck(oldRuleCheck);
                }
            }
            // 更新规则复核
            String status = params.getStatus();
            if(ajRule.getIsAdd().equals("1")){
                status = "6";
            }
            AjRuleCheck oldRuleCheck = new AjRuleCheck();
            oldRuleCheck.setId(id.intValue());
            oldRuleCheck.setCheckTime(new Date());
            oldRuleCheck.setStatus(status);
            oldRuleCheck.setRemark(params.getRemark());
            oldRuleCheck.setVersion(String.format("v" + DateUtils.parseDateToStr("yyyy-MM-dd", DateUtils.addDays(ajRuleCheck.getActiveDate(), -1)) + "000000"));
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                oldRuleCheck.setCheckor(loginUser.getUsername());
                oldRuleCheck.setCheckorId(loginUser.getUserId().intValue());
            }
            ruleCheckMapper.updateRuleCheck(oldRuleCheck);
            // 删除上一个生效的版本
            List<AjRuleCheck> ajRuleChecks = ruleCheckMapper.selectRuleCheckList(new AjRuleCheck() {{
                setRuleId(ajRule.getId());
                setStatusNames("7");
            }});
            // 删除之前生效的版本
            if (!CollectionUtils.isEmpty(ajRuleChecks)) {
                for(AjRuleCheck check : ajRuleChecks) {
                    ruleCheckMapper.deleteRuleCheckById(check.getId().longValue());
                }
            }
        }
        return 1;
    }

    private void copyRuleDetail(AjRule rule, AjRuleCheck check) {
        if (rule.getRuleDetailId() != null) {
            AjRuleDetail detail = ruleDetailMapper.selectRuleDetailById(rule.getRuleDetailId());
            if (detail == null) {
                throw new ServiceException("未找到该规则明细");
            }
            check.setRuleDetailId(detail.getId().longValue());
            check.setRuleDetailAlert(detail.getAlert());
            check.setRuleDetailEditor(detail.getEditor());
            check.setRuleDetailRuleGroup(detail.getRuleGroup());
            check.setRuleDetailAttachCate(detail.getAttachCate());
            check.setRuleDetailDesc(detail.getDesc());
        }

    }
}
